package com.book.framework.security.filter;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.book.common.core.domain.model.AppLoginUser;
import com.book.common.core.domain.model.LoginUser;
import com.book.common.utils.SecurityUtils;
import com.book.common.utils.StringUtils;
import com.book.framework.web.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * token过滤器 验证token有效性
 * 
 * @author ruoyi
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter
{
    //推荐创建不可变静态类成员变量
    private static final Log log = LogFactory.get(JwtAuthenticationTokenFilter.class);

    @Autowired
    private TokenService tokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException
    {
        // 获取请求路径
        String requestURI = request.getRequestURI();
        // 获取 context-path
        String contextPath = request.getContextPath();
        //去除掉context-path后的路径
        String path = requestURI.substring(contextPath.length());

        //特殊路径判断
        if ("/common/upload".equals(path)) {
            // 直接获取 LoginUser 和 AppLoginUser
            LoginUser loginUser = tokenService.getLoginUser(request);
            AppLoginUser appLoginUser = tokenService.getAppLoginUser(request);

            // 判断是否存在有效的 token
            if (StringUtils.isNotNull(loginUser)) {
                originalAuthLogic(request);
            }
            if(StringUtils.isNotNull(appLoginUser)){
                appAuthLogic(request);
            }
            chain.doFilter(request, response);
            return;
        }
        if(path.startsWith("/app/")){
            //注意app的接口必须以/app/开头
            appAuthLogic(request);
        }else{
            originalAuthLogic(request);
        }
        chain.doFilter(request, response);
    }

    /**
     * 原先框架的鉴权逻辑
     * @param request
     */
    private void originalAuthLogic(HttpServletRequest request){
        log.info("执行后台系统的鉴权");
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication()))
        {
            tokenService.verifyToken(loginUser);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
    }


    /**
     * app的鉴权逻辑
     * @param request
     */
    private void appAuthLogic(HttpServletRequest request){
        log.info("执行app的鉴权");
        AppLoginUser appLoginUser = tokenService.getAppLoginUser(request);
        if (StringUtils.isNotNull(appLoginUser) && StringUtils.isNull(SecurityUtils.getAuthentication()))
        {
            tokenService.verifyAppToken(appLoginUser);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(appLoginUser, null, appLoginUser.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
    }
}
